/**
 * 📊 智能分析页面逻辑
 * 财务健康评分、异常检测、习惯分析
 */

// 全局变量
let currentBookId = null;
let charts = {};

// 初始化
document.addEventListener('DOMContentLoaded', async function() {
    console.log('📊 智能分析页面初始化');
    
    // 检查登录状态
    if (!API.isLoggedIn()) {
        showToast('请先登录', 'error');
        setTimeout(() => {
            window.location.href = 'login.html';
        }, 1500);
        return;
    }

    // 获取当前账本ID
    currentBookId = localStorage.getItem('currentBookId');
    if (!currentBookId) {
        showToast('请先选择账本', 'warning');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1500);
        return;
    }

    // 设置默认时间范围（最近30天）
    setQuickRange('month');
    
    // 加载分析数据
    await loadAnalysisData();
});

/**
 * 设置快捷时间范围
 */
function setQuickRange(range) {
    const endDate = new Date();
    let startDate = new Date();
    
    switch(range) {
        case 'month':
            startDate.setDate(1); // 本月1号
            break;
        case '3months':
            startDate.setMonth(startDate.getMonth() - 2);
            startDate.setDate(1);
            break;
        case 'year':
            startDate.setMonth(0);
            startDate.setDate(1);
            break;
    }
    
    document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
    document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
}

/**
 * 加载分析数据
 */
async function loadAnalysisData() {
    try {
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        
        if (!startDate || !endDate) {
            showToast('请选择时间范围', 'warning');
            return;
        }

        showToast('正在分析数据...', 'info');

        // 并行加载所有分析数据
        const [healthScoreData, habitsData, anomaliesData] = await Promise.all([
            loadHealthScore(startDate, endDate),
            loadHabits(startDate, endDate),
            loadAnomalies()
        ]);

        showToast('分析完成！', 'success');

    } catch (error) {
        console.error('加载分析数据失败:', error);
        showToast('加载失败：' + error.message, 'error');
    }
}

/**
 * 加载健康评分
 */
async function loadHealthScore(startDate, endDate) {
    try {
        const response = await API.get(
            `/analysis/health-score?book_id=${currentBookId}&start_date=${startDate}&end_date=${endDate}`
        );
        
        if (response.code === 200) {
            displayHealthScore(response.data);
            return response.data;
        } else {
            throw new Error(response.message || '获取健康评分失败');
        }
    } catch (error) {
        console.error('加载健康评分失败:', error);
        throw error;
    }
}

/**
 * 显示健康评分
 */
function displayHealthScore(data) {
    // 显示总分
    document.getElementById('totalScore').textContent = data.total_score.toFixed(1);
    
    // 显示评级
    let level = '需改进';
    let levelColor = '#f44336';
    if (data.total_score >= 80) {
        level = '优秀';
        levelColor = '#4CAF50';
    } else if (data.total_score >= 60) {
        level = '良好';
        levelColor = '#2196F3';
    } else if (data.total_score >= 40) {
        level = '及格';
        levelColor = '#ff9800';
    }
    
    document.getElementById('scoreLevel').textContent = `评级：${level}`;
    document.getElementById('scoreLevel').style.color = levelColor;
    
    // 显示各维度得分
    document.getElementById('savingScore').textContent = `${data.saving_rate_score.toFixed(1)} / 30`;
    document.getElementById('rationalityScore').textContent = `${data.rationality_score.toFixed(1)} / 30`;
    document.getElementById('executionScore').textContent = `${data.execution_score.toFixed(1)} / 20`;
    document.getElementById('stabilityScore').textContent = `${data.stability_score.toFixed(1)} / 20`;
    
    // 显示建议
    displaySuggestions(data.suggestions);
}

/**
 * 显示改进建议
 */
function displaySuggestions(suggestions) {
    const container = document.getElementById('suggestions');
    
    if (!suggestions || suggestions.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无建议，财务状况良好！</div>';
        return;
    }
    
    const html = suggestions.map(s => `
        <div class="suggestion-card priority-${s.priority}">
            <h4>${s.icon} ${s.title}</h4>
            <p>${s.content}</p>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

/**
 * 加载异常检测
 */
async function loadAnomalies() {
    try {
        const response = await API.get(
            `/analysis/anomalies?book_id=${currentBookId}&status=pending&limit=20`
        );
        
        if (response.code === 200) {
            displayAnomalies(response.data);
            return response.data;
        } else {
            throw new Error(response.message || '获取异常检测失败');
        }
    } catch (error) {
        console.error('加载异常检测失败:', error);
        throw error;
    }
}

/**
 * 显示异常列表
 */
function displayAnomalies(anomalies) {
    const container = document.getElementById('anomalyList');
    
    if (!anomalies || anomalies.length === 0) {
        container.innerHTML = '<li class="empty-state">✅ 未检测到异常消费</li>';
        return;
    }
    
    const html = anomalies.map(a => `
        <li class="anomaly-item severity-${a.severity}">
            <div class="anomaly-title">${a.description}</div>
            <div class="anomaly-meta">
                📅 ${new Date(a.date).toLocaleDateString()}
                | 💰 ￥${parseFloat(a.amount).toFixed(2)}
                | 🏷️ ${a.category}
                | 🔍 置信度：${a.confidence}%
            </div>
            <div class="anomaly-actions">
                <button class="btn btn-sm btn-danger" onclick="handleAnomaly(${a.id}, 'confirmed')">
                    ✓ 确认异常
                </button>
                <button class="btn btn-sm btn-secondary" onclick="handleAnomaly(${a.id}, 'ignored')">
                    ✗ 忽略
                </button>
            </div>
        </li>
    `).join('');
    
    container.innerHTML = html;
}

/**
 * 处理异常
 */
async function handleAnomaly(anomalyId, action) {
    try {
        const response = await API.post(`/analysis/anomalies/${anomalyId}/action`, { action });
        
        if (response.code === 200) {
            showToast('操作成功', 'success');
            await loadAnomalies(); // 重新加载
        } else {
            throw new Error(response.message || '操作失败');
        }
    } catch (error) {
        console.error('处理异常失败:', error);
        showToast('操作失败：' + error.message, 'error');
    }
}

/**
 * 加载习惯分析
 */
async function loadHabits(startDate, endDate) {
    try {
        const response = await API.get(
            `/analysis/habits?book_id=${currentBookId}&start_date=${startDate}&end_date=${endDate}`
        );
        
        if (response.code === 200) {
            displayHabitAnalysis(response.data);
            return response.data;
        } else {
            throw new Error(response.message || '获取习惯分析失败');
        }
    } catch (error) {
        console.error('加载习惯分析失败:', error);
        throw error;
    }
}

/**
 * 显示习惯分析
 */
function displayHabitAnalysis(data) {
    // 显示消费模式总结（新增）
    if (data.consumptionSummary) {
        displayConsumptionSummary(data.consumptionSummary);
    }
    
    // 小时分布图
    renderHourlyChart(data.timeAnalysis.hourly);
    
    // 星期分布图
    renderWeeklyChart(data.timeAnalysis.weekly);
    
    // 类别饼图
    renderCategoryChart(data.categoryAnalysis);
    
    // 趋势图
    renderTrendChart(data.trendAnalysis);
}

/**
 * 渲染24小时消费分布图
 */
function renderHourlyChart(hourlyData) {
    const chartDom = document.getElementById('hourlyChart');
    if (!chartDom) return;
    
    // 销毁旧图表
    if (charts.hourly) {
        charts.hourly.dispose();
    }
    
    charts.hourly = echarts.init(chartDom);
    
    const hours = Array.from({length: 24}, (_, i) => i);
    const dataMap = {};
    hourlyData.forEach(d => {
        dataMap[d.hour] = d.amount;
    });
    const amounts = hours.map(h => dataMap[h] || 0);
    
    const option = {
        title: {
            text: '24小时消费热力图',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: (params) => {
                const hour = params[0].axisValue;
                const amount = params[0].data;
                return `${hour}点：￥${amount.toFixed(2)}`;
            }
        },
        xAxis: {
            type: 'category',
            data: hours.map(h => `${h}点`),
            axisLabel: {
                interval: 2
            }
        },
        yAxis: {
            type: 'value',
            name: '金额(元)',
            axisLabel: {
                formatter: '¥{value}'
            }
        },
        series: [{
            data: amounts,
            type: 'bar',
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#83bff6' },
                    { offset: 1, color: '#188df0' }
                ])
            },
            emphasis: {
                itemStyle: {
                    color: '#188df0'
                }
            }
        }]
    };
    
    charts.hourly.setOption(option);
}

/**
 * 渲染星期消费分布图
 */
function renderWeeklyChart(weeklyData) {
    const chartDom = document.getElementById('weeklyChart');
    if (!chartDom) return;
    
    if (charts.weekly) {
        charts.weekly.dispose();
    }
    
    charts.weekly = echarts.init(chartDom);
    
    const option = {
        title: {
            text: '星期消费对比',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: (params) => {
                const day = params[0].axisValue;
                const amount = params[0].data;
                return `${day}：￥${amount.toFixed(2)}`;
            }
        },
        xAxis: {
            type: 'category',
            data: weeklyData.map(d => d.day)
        },
        yAxis: {
            type: 'value',
            name: '金额(元)',
            axisLabel: {
                formatter: '¥{value}'
            }
        },
        series: [{
            data: weeklyData.map(d => d.amount),
            type: 'line',
            smooth: true,
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(52, 168, 83, 0.3)' },
                    { offset: 1, color: 'rgba(52, 168, 83, 0.05)' }
                ])
            },
            lineStyle: {
                width: 3,
                color: '#34a853'
            },
            itemStyle: {
                color: '#34a853'
            }
        }]
    };
    
    charts.weekly.setOption(option);
}

/**
 * 渲染类别饼图
 */
function renderCategoryChart(categoryData) {
    const chartDom = document.getElementById('categoryChart');
    if (!chartDom) return;
    
    if (charts.category) {
        charts.category.dispose();
    }
    
    charts.category = echarts.init(chartDom);
    
    const option = {
        title: {
            text: '消费类别分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: ￥{c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
        },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: true,
                formatter: '{b}: {d}%'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            data: categoryData.map(d => ({
                name: d.category,
                value: d.amount
            }))
        }]
    };
    
    charts.category.setOption(option);
}

/**
 * 渲染趋势图
 */
function renderTrendChart(trendData) {
    const chartDom = document.getElementById('trendChart');
    if (!chartDom) return;
    
    if (charts.trend) {
        charts.trend.dispose();
    }
    
    charts.trend = echarts.init(chartDom);
    
    const months = trendData.map(d => d.month);
    const income = trendData.map(d => d.income);
    const expense = trendData.map(d => d.expense);
    
    // 如果有预测数据
    let predictedMonths = [];
    let predictedExpense = [];
    if (trendData.predictions && trendData.predictions.length > 0) {
        predictedMonths = trendData.predictions.map(p => p.month);
        predictedExpense = trendData.predictions.map(p => p.predicted_expense);
    }
    
    const option = {
        title: {
            text: '收支趋势分析',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            formatter: (params) => {
                let result = `${params[0].axisValue}<br/>`;
                params.forEach(p => {
                    result += `${p.seriesName}: ￥${p.data.toFixed(2)}<br/>`;
                });
                return result;
            }
        },
        legend: {
            data: ['收入', '支出', '预测支出'],
            top: 30
        },
        grid: {
            top: 80,
            bottom: 60
        },
        xAxis: {
            type: 'category',
            data: [...months, ...predictedMonths]
        },
        yAxis: {
            type: 'value',
            name: '金额(元)',
            axisLabel: {
                formatter: '¥{value}'
            }
        },
        series: [
            {
                name: '收入',
                type: 'line',
                data: [...income, ...Array(predictedMonths.length).fill(null)],
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#4CAF50'
                },
                itemStyle: {
                    color: '#4CAF50'
                }
            },
            {
                name: '支出',
                type: 'line',
                data: [...expense, ...Array(predictedMonths.length).fill(null)],
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#f44336'
                },
                itemStyle: {
                    color: '#f44336'
                }
            },
            {
                name: '预测支出',
                type: 'line',
                data: [...Array(months.length).fill(null), ...predictedExpense],
                smooth: true,
                lineStyle: {
                    width: 2,
                    type: 'dashed',
                    color: '#ff9800'
                },
                itemStyle: {
                    color: '#ff9800'
                }
            }
        ]
    };
    
    charts.trend.setOption(option);
}

/**
 * 显示消费模式总结（新增）
 */
function displayConsumptionSummary(summaryData) {
    const section = document.getElementById('consumptionSummarySection');
    const container = document.getElementById('consumptionInsights');
    
    if (!section || !container || !summaryData || !summaryData.summary) {
        return;
    }
    
    // 显示区域
    section.style.display = 'block';
    
    // 清空容器
    container.innerHTML = '';
    
    // 渲染每个洞察卡片
    summaryData.summary.forEach(insight => {
        const card = document.createElement('div');
        card.className = 'insight-card';
        
        // 根据level设置不同的样式
        let borderColor = '#4CAF50'; // 默认绿色
        let bgColor = '#f1f8f4';
        
        if (insight.level === 'warning') {
            borderColor = '#ff9800';
            bgColor = '#fff8e1';
        } else if (insight.level === 'danger') {
            borderColor = '#f44336';
            bgColor = '#ffebee';
        } else if (insight.level === 'high') {
            borderColor = '#2196F3';
            bgColor = '#e3f2fd';
        }
        
        card.style.cssText = `
            padding: 20px;
            border-left: 4px solid ${borderColor};
            background: ${bgColor};
            border-radius: 8px;
            transition: all 0.3s;
        `;
        
        card.innerHTML = `
            <div style="display: flex; align-items: flex-start; gap: 15px;">
                <div style="font-size: 32px; flex-shrink: 0;">
                    ${getInsightIcon(insight.type)}
                </div>
                <div style="flex: 1;">
                    <h4 style="margin: 0 0 10px 0; color: #333; font-size: 18px;">
                        ${insight.title}
                    </h4>
                    <p style="margin: 0; color: #666; line-height: 1.6; white-space: pre-wrap;">
                        ${insight.content}
                    </p>
                </div>
            </div>
        `;
        
        // 悬停效果
        card.addEventListener('mouseenter', () => {
            card.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
            card.style.transform = 'translateX(5px)';
        });
        
        card.addEventListener('mouseleave', () => {
            card.style.boxShadow = 'none';
            card.style.transform = 'translateX(0)';
        });
        
        container.appendChild(card);
    });
    
    // 如果有统计数据，也可以显示
    if (summaryData.statistics) {
        const statsCard = document.createElement('div');
        statsCard.style.cssText = `
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            margin-top: 15px;
        `;
        
        const stats = summaryData.statistics;
        statsCard.innerHTML = `
            <h4 style="margin: 0 0 15px 0;">📊 统计概览</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">总记录数</div>
                    <div style="font-size: 24px; font-weight: bold;">${stats.total_records}笔</div>
                </div>
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">总收入</div>
                    <div style="font-size: 24px; font-weight: bold;">¥${stats.total_income.toFixed(2)}</div>
                </div>
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">总支出</div>
                    <div style="font-size: 24px; font-weight: bold;">¥${stats.total_expense.toFixed(2)}</div>
                </div>
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">储蓄率</div>
                    <div style="font-size: 24px; font-weight: bold;">${stats.saving_rate.toFixed(1)}%</div>
                </div>
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">平均每笔支出</div>
                    <div style="font-size: 24px; font-weight: bold;">¥${stats.avg_expense.toFixed(2)}</div>
                </div>
                <div>
                    <div style="font-size: 12px; opacity: 0.8;">日均消费笔数</div>
                    <div style="font-size: 24px; font-weight: bold;">${stats.daily_expense_count.toFixed(1)}笔</div>
                </div>
            </div>
        `;
        
        container.appendChild(statsCard);
    }
    
    // 如果有商户数据，显示Top商户
    if (summaryData.top_merchants && summaryData.top_merchants.length > 0) {
        const merchantCard = document.createElement('div');
        merchantCard.style.cssText = `
            padding: 20px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            margin-top: 15px;
        `;
        
        let merchantHTML = '<h4 style="margin: 0 0 15px 0;">🏪 常去商户Top5</h4><div style="display: grid; gap: 10px;">';
        
        summaryData.top_merchants.slice(0, 5).forEach((merchant, index) => {
            merchantHTML += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: #f9f9f9; border-radius: 6px;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="font-weight: bold; color: #666;">#${index + 1}</span>
                        <span style="color: #333;">${merchant.merchant}</span>
                    </div>
                    <div style="text-align: right;">
                        <div style="color: #333; font-weight: bold;">¥${merchant.amount.toFixed(2)}</div>
                        <div style="color: #999; font-size: 12px;">${merchant.count}笔</div>
                    </div>
                </div>
            `;
        });
        
        merchantHTML += '</div>';
        merchantCard.innerHTML = merchantHTML;
        container.appendChild(merchantCard);
    }
}

/**
 * 根据洞察类型返回对应的emoji图标
 */
function getInsightIcon(type) {
    const iconMap = {
        'income_expense': '💰',
        'saving_rate': '🏦',
        'main_category': '🍽️',
        'merchants': '🏪',
        'frequency': '📊',
        'income_pattern': '💸'
    };
    return iconMap[type] || '📈';
}

// 响应式图表
window.addEventListener('resize', () => {
    Object.values(charts).forEach(chart => {
        if (chart) chart.resize();
    });
});

